//
//  WJPublishAudioVC.m
//  WJBSApp
//
//  Created by dllo on 16/8/1.
//  Copyright © 2016年 王景伟. All rights reserved.
//

#import "WJPublishAudioVC.h"
#import "WJTextView.h"
#import "WJDataManager.h"
#import "WJPublishModel.h"
#import <AVFoundation/AVFoundation.h>

@interface WJPublishAudioVC ()<UITextViewDelegate>

@property (nonatomic,strong) WJBaseView *touView;

@property (nonatomic,strong) WJTextView *textView;

@property (nonatomic,strong) WJBaseButton *rightbutton;

@property (nonatomic,strong) WJBaseButton *chooseButton;
/** 定时器 */
@property (nonatomic,strong) NSTimer *timer;
/** 显示时间的Lable */
@property (nonatomic,strong) WJBaseLable *timeLable;

@property (nonatomic,assign) BOOL isClick;
/** 录音要使用的属性 */
@property (nonatomic,strong) AVAudioRecorder *recorder;
/** 记录放置录音的路径 */
@property (nonatomic,copy) NSString *path;
@end

@implementation WJPublishAudioVC



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.textView becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createView];
    
    [self createTextView];
}

 /** 导航栏 */
- (void)createView
{
    self.touView = [[WJBaseView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    [self.view addSubview:self.touView];
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 24, WIDTH - 200, 40)];
    lable.text = @"发表声音";
    lable.textAlignment = 1 ;
    [self.touView addSubview:lable];
    
    WJBaseButton *button = [WJBaseButton buttonWithTitle:nil frame:CGRectMake(20, 30, 50, 30) target:self action:@selector(puLeftAction)];
    button.backgroundColor = BSClearColor;
    [button setImage:[UIImage imageNamed:@"navigationButtonReturn.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"navigationButtonReturnClick.png"] forState:UIControlStateHighlighted];
    [self.touView addSubview:button];
    
    self.rightbutton = [WJBaseButton buttonWithTitle:@"发表" frame:CGRectMake(WIDTH - 70, 30, 50, 30) target:self action:@selector(puRightAction)];
    [ self.rightbutton setTitleColor:BSBlackColor forState:0];
    self.rightbutton.backgroundColor = BSClearColor;
    [self.touView addSubview: self.rightbutton];
    [self.touView layoutIfNeeded];
    
}

 /** 下面的部分 */
- (void)createTextView
{
    self.textView = [[WJTextView alloc]initWithFrame:CGRectMake(15, 64, WIDTH - 30, HEIGHT * 2 / 7)];
    [self.view addSubview:self.textView];
    _textView.alwaysBounceVertical = YES;
    _textView.delegate = self;
    _textView.placeholder = @"这里添加文字,请勿发布色情、政治等违反国家法律的内容,违者封号处理";
    self.editing = YES;
    self.textView.userInteractionEnabled = YES;
    
    self.chooseButton = [WJBaseButton buttonWithType:UIButtonTypeSystem];
    self.chooseButton.frame = CGRectMake(WIDTH / 2-50, 94 + HEIGHT * 2 / 7, 100, 30);
    [self.chooseButton setTitle:@"点击录制" forState:UIControlStateNormal];
    [self.chooseButton addTarget:self action:@selector(buttonAct:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.chooseButton];
    self.isClick = YES;
    
    self.timeLable = [[WJBaseLable alloc]initWithFrame:CGRectMake(WIDTH / 2 - 140, 94 + HEIGHT * 2 / 7, 80, 30)];
    [self.view addSubview:self.timeLable];
    self.timeLable.text = @"00:00.00";
    
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
        //7.0第一次运行会提示，是否允许使用麦克风
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if(session == nil)
            NSLog(@"Error creating session: %@", [sessionError description]);
        else
            [session setActive:YES error:nil];
    }
    
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如：AVSampleRateKey==8000/44100/96000（影响音频的质量）
    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
   /** 首先将录音的文件放入temp文件中 目的:1.不发表的话 退出app就清空它 2.发表的话在写入本地 */
   _path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/aaa"];
    NSURL* url = [NSURL fileURLWithPath:_path];
    
    _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:nil];
    //准备录音
    [_recorder prepareToRecord];


    
}

 /** 点击返回 */
- (void)puLeftAction
{
    [self.textView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 开始录音
- (void)buttonAct:(WJBaseButton *)button
{
    if (self.isClick) {
        // 开始录音
        [_recorder record];
        [button setTitle:@"结束" forState:0];
        //启动定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(levelTimer:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        
        self.isClick = NO;
    }else{
        [button setTitle:@"录制完成" forState:0];
        // 结束录音
        [_recorder stop];
        [self.timer invalidate];
        self.timer = nil;
    }
}

 /** lable要显示的文字 */
- (void)levelTimer:(NSTimer *)time
{
    self.timeLable.text = [self withTime:[NSString stringWithFormat:@"%f",self.recorder.currentTime]];
}

- (NSString *)withTime:(NSString *)time
{
    NSInteger timeValue = time.floatValue *100;
    
    // 毫秒
    NSInteger ms = timeValue % 100;
    
    // 秒
    NSInteger sec = time.integerValue % 60;
    
    // 分
    NSInteger min = time.integerValue / 60;
    
    return [NSString stringWithFormat:@"%02zd:%02zd:%ld",min,sec,(long)ms];
}


/** 点击发表进入本地 录音的格式为Caf*/
- (void)puRightAction
{
    NSLog(@"点击了发表");
    [self.textView resignFirstResponder];
    
    
    /** 判断不为空则可以发表 */
    if (self.textView.text) {
        
        /** 因为我们要用text来删除文件所以必须要有文字*/
        if (self.textView.text) {
            
            
            NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
            NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
            dateFormatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
            NSString *currentDateStr = [dateFormatter stringFromDate:detaildate];
            
            NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/aaa"];
            NSURL* url = [NSURL fileURLWithPath:path];
            NSData *data = [NSData dataWithContentsOfURL:url];
            
            // 这一句好像必须写
            [data writeToFile:[NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp/aaa"] atomically:YES];
            
            /** 时间戳用来给文件命名 */
            NSString *dataPath = [VIDEO stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.aaa",currentDateStr]];
            
            
            BOOL result = [[NSFileManager defaultManager] copyItemAtPath:path toPath:dataPath error:nil];;
            
            if (result) {
                NSLog(@"拷贝到本地成功了");
                NSLog(@"%@",dataPath);
            }
            
            WJPublishModel *model = [[WJPublishModel alloc]init];
            model.type = @"audio";
            model.text = self.textView.text;
            model.nowTime = currentDateStr;
            model.audioPath = dataPath;
            model.totalTime = [self.timeLable.text substringToIndex:5];
            [[WJDataManager shareFMDB]insertModel:model];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"发表成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
                [self dismissViewControllerAnimated:YES completion:nil];
                
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:^{}];
            
        }else{
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请填写描述文字" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {}];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:^{}];
            
        }
        
    }else{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"没有录音" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {}];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{}];
        
    }
    
}

#pragma mark -- UITextFieldDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //拖拽时 结束编辑 退出键盘
    [self.textView endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        self.textView.frame = CGRectMake(15, 64, WIDTH - 30, HEIGHT - 64 - 150);
        self.chooseButton.frame = CGRectMake(WIDTH / 2-50, HEIGHT - 100, 100, 30);
        self.timeLable.frame =CGRectMake(WIDTH / 2 - 140, HEIGHT - 100, 80, 30);
    }];
}

- (void)textViewDidChange:(UITextView *)textView{
    //判读是否有文字  设置发表按钮的状态
    self.rightbutton.enabled = textView.hasText;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    [UIView animateWithDuration:0.5 animations:^{
        self.textView.frame = CGRectMake(15, 64, WIDTH - 30, HEIGHT * 2 / 7);
        self.chooseButton.frame = CGRectMake(WIDTH / 2-50, 94 + HEIGHT * 2 / 7 , 100, 30);
        self.timeLable.frame =CGRectMake(WIDTH / 2 - 140, 94 + HEIGHT * 2 / 7, 80, 30);
    }];
    return YES;
}



@end
